/**
 * Bakalarska prace - Inteligentni budik
 * @package sleepCatcher
 * @file SCResampler.cpp
 * @author Jan Pesava - xpesav00
 * @email xpesav00@stud.fit.vutbr.cz
 * @date 2. 4. 2012
 */

#include "models/SCResampler.h"
#include "models/SCHelpers.h"

SCResampler::SCResampler(int resampledIndex, bool deleteUnusedSamples)
{
	this->resampledIndex = resampledIndex;
	this->deleteUnusedSamples = deleteUnusedSamples;

	//Init
	this->Init();
}

SCResampler::~SCResampler()
{
}

SCSample*
SCResampler::AddSample(SCSample* pSample)
{
	SCSample* pResampledSample;

	//increment counter
	this->sampleCounter++;

	this->ExecuteResampling(pSample);

	if((this->sampleCounter % this->resampledIndex) == 0)
	{
		pResampledSample = this->pBaseSample;
		this->pBaseSample = NULL;
	} else {
		pResampledSample = NULL;
	}

	return pResampledSample;
}

void
SCResampler::ExecuteResampling(SCSample* pSample)
{
	if(this->pBaseSample == NULL)
	{
		this->pBaseSample = SCHelpers::CloneSample(pSample);
	} else {
		this->pBaseSample->SetEnergy((this->pBaseSample->GetEnergy() + pSample->GetEnergy()) / 2);
		this->pBaseSample->SetSoundValue((this->pBaseSample->GetSoundValue() + pSample->GetSoundValue()) / 2);
		this->pBaseSample->SetWindowEnergy((this->pBaseSample->GetWindowEnergy() + pSample->GetWindowEnergy()) / 2);
		this->pBaseSample->SetXaxis((this->pBaseSample->GetXaxis() + pSample->GetXaxis()) / 2);
		this->pBaseSample->SetYaxis((this->pBaseSample->GetYaxis() + pSample->GetYaxis()) / 2);
		this->pBaseSample->SetZaxis((this->pBaseSample->GetZaxis() + pSample->GetZaxis()) / 2);
	}

	if(this->deleteUnusedSamples)
	{
		delete pSample;
	}
}

void
SCResampler::Init()
{
	this->pBaseSample = NULL;
	this->sampleCounter = 0;
}

void
SCResampler::StartCatch()
{
	this->Init();
}

void
SCResampler::StopCatch()
{
	if(this->pBaseSample != NULL)
	{
		delete this->pBaseSample;
		this->pBaseSample = NULL;
	}
}
